/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-17 8:59:15
 ******************************************************************************/
package cn.com.xy.sms.sdk.net;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.IccidInfo;
import cn.com.xy.sms.sdk.db.entity.IccidInfoManager;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.util.Base64;
import cn.com.xy.sms.sdk.net.util.RSAUtils;
import cn.com.xy.sms.sdk.net.util.ServerUtil;
import cn.com.xy.sms.sdk.util.KeyManager;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;

/* SDK-428 huangzhiqiang 20160602 start */
import cn.com.xy.sms.sdk.util.CallBackState;
import cn.com.xy.sms.util.SdkCallBack;



/* SDK-428 huangzhiqiang 20160602 end */
/* SDK-526 huangzhiqiang 20160707 start */
import android.text.TextUtils;
import android.util.LruCache;
/* SDK-526 huangzhiqiang 20160707 end */

/*SDK-616 hewengao/20160918 start*/
import cn.com.xy.sms.sdk.threadpool.SmartSmsThreadPoolManager;
/*SDK-616 hewengao/20160918 end*/

public class NetUtil {
    // public static String serverUrl = "http://smssdk"+(int) (Math.random() *
    // 10+1)+".duoqu.in/popupservice/api/";
    // public static String serverUrl =
    // "http://192.168.1.156:8880/popupservice";
    // public static String serverUrl2 =
    // "http://192.168.1.211:8080/publicNumService";//获取服务器的公众号数据
    // public static String serverUrl2
    // ="http://192.168.1.113:8080//publicNumService/";
    // public static String prex = "http://down1.duoqu.in";
    public static String STATSERVICE_URL = "http://scene" + (int) (Math.random() * 10 + 1) + ".bizport.cn:8981/statservice/stat/";
    public static String serverUrl2 = "http://pubserver" + (int) (Math.random() * 10 + 1) + ".bizport.cn:9998/pubNumService/";
    public static String serverUrl = "http://smssdk" + (int) (Math.random() * 10 + 1) + ".bizport.cn/popupservice/api/";
    public static String prex = "http://down1.bizport.cn";
    /*SDK-564 hewengao 20160726 start*/
    public static String BIZPORT_DOWN_URL = "http://down2.bizport.cn/publicnum/upload/";
    /*SDK-564 hewengao 20160726 end*/
    public static String PUBINFO_SERVER_URL_HTTPS = "https://pubapi" + (int) (Math.random() * 10 + 1) + ".bizport.cn:9443/pubNumService/";
    public static String POPUP_SERVER_URL_HTTPS = "https://sdkapi" + (int) (Math.random() * 10 + 1) + ".bizport.cn:8943/popupservice/";
    
//    public static String publicInfoServerUrl = "http://olapi.bizport.cn/";//在线查询运营商指令、在线识别运营商短信的URL
    public static String publicInfoServerUrl = "http://olapi" + (int) (Math.random() * 10 + 1) + ".bizport.cn/";
    /* KINGMAIL-46 huangzhiqiang 20170417 start */
    public static String PUBLIC_INFO_SERVER_URL_HTTPS = "https://olapi" + (int) (Math.random() * 10 + 1) + ".bizport.cn/";
    /* KINGMAIL-46 huangzhiqiang 20170417 end */
    // public static String serverUrl ="http://192.168.1.156:8880/popupservice";
    // public static String prex = "http://192.168.1.156:8080";

    // public static String checkRes = "http://pubserver"+(int) (Math.random() *
    // 10+1)+".bizport.cn:9998/pubNumService/checkResourseRequest/";

    /*SDK-565 zhaojiangwei 20160726 start */
    public static final int HTTP_NO_BODYDATA = -5; // http返回的响应长度为0
    /*SDK-565 zhaojiangwei 20160726 end */
    
    public static final int HTTP_CONN_OUTTIME = -6; // http连接超时

    public static final int HTTP_THROWS_EXCEPTION = -7; // http抛出异常

    public static final int HTTP_ACCESS_FALIE = -8; // http访问失败d

    public static final int HTTP_PACKAGE_TO_BIG = -9;// http包过大
    
    /*SMARTISAN-136 zhaojiangwei 20160829 start */
    public static final int HTTP_SSL_EXCEPTION = -12; // HTTS 证书验证错误
    /*SMARTISAN-136 zhaojiangwei 20160829 end */
   
    public static String APPVERSION = "201705051719";// SDK版本号
    // public static String APPVERSION ="201510100900";//修改算法为SHA256WithRSA
    public static final String REQ_QUERY_TOEKN = "token";
    public static final String REQ_QUERY_PUBINFO = "pubinfo";
    public static final String REQ_QUERY_MENUINFO = "menuinfo";
    public static final String REQ_QUERY_LOCATION = "location";
    public static final String REQ_QUERY_CHECI = "checi";
    /* SDK-428 huangzhiqiang 20160530 start */
    public static final String REQ_QUERY_NUM = "phonenum";
    public static final String REQ_NUM_MARK = "phonemark";
    /* SDK-428 huangzhiqiang 20160530 end */
    
    public static final String REQ_QUERY_OPERATOR = "opinfo";
    public static final String REQ_QUERY_OPERATOR_MSG = "opanalysis";
    public static final String URL_VALIDITY = "URLValidity";
    public static final String URL_MENU_CLICKED = "menuclick";//菜单点击
    public static final String URL_PUB_NUMBER = "pubnumber";
    /* RM-1290 mobaohua 20170406 start */
    public static final String URL_MSG_MOVIE = "messagemovie";
    /* RM-1290 mobaohua 20170406 end */
    /* SDK-765 mobaohua 20170419 start */
    public static final String URL_EXPRESS_INFO = "express";
    /* SDK-765 mobaohua 20170419 end */
	/* IMOO-9 likuangkuang 20161014 start */
	public static final String REQ_QUERY_UPGRADE = "phoneupgrade";
	/* IMOO-9 likuangkuang 20161014 end */
    
    /*SDK-431 songzhirong 20160530 start*/
    public static final String URL_LOG_SERVICE = "logserver";
    /*SDK-431 songzhirong 20160530 end*/

    /* RM-1374 mobaohua 20170314 start */
    public static final String URL_PREVIEW_SERVICE = "urlIdent2";
    /* RM-1374 mobaohua 20170314 end */

    public static final String UpdateRecognitionJarRequest = "updatejar";
    public static final String QuerySceneRequest = "queryscene";
    public static final String UpdatePublicInfoRequest = "updatepublic";
    public static final String CheckResourseRequest = "checkResourseRequest";
    
    /*SDK-680 zhaojiangwei 20161117 start*/
    public static final String GET_PHONE_MENU = "phonemenu";
    /*SDK-680 zhaojiangwei 20161117 start*/

    /* KINGMAIL-67 huangzhiqiang 20170411 start */
    public static String REQ_TRAVEL = "staticData";
    /* KINGMAIL-67 huangzhiqiang 20170411 end */

    /* KINGMAIL-49 huangzhiqiang 20170411 start */
    public static String REQ_EMAIL_MENU = "entInfo";
    /* KINGMAIL-49 huangzhiqiang 20170411 end */

    static String locationUrl = "";
//    public static ExecutorService pool = Executors.newFixedThreadPool(1);

    /* KINGMAIL-49 huangzhiqiang 20170411 start */
    private static Map<String, String> mEmailMenuServiceExtend = null;
    /* KINGMAIL-49 huangzhiqiang 20170411 end */

    public static void executeRunnable(Runnable runnable) {
        /*SDK-616 hewengao/20160918 start*/
        SmartSmsThreadPoolManager.pool.execute(runnable);
        /*SDK-616 hewengao/20160918 end*/
    }

    /**
     * 检测使用网络的权限
     * 
     * @return
     */
     public static boolean checkAccessNetWork() {
     return checkAccessNetWork(2);
     }

    /**
     * 检测当前使用的业务，是否能访问对应的业务。
     * 
     * @param nType
     *            1:仅wifi下才能访问对应的业务 2:任意网络都可以访问对应的业务。 但是还需要受用户设置的网络开关控制。
     * @return
     */
    public static boolean checkAccessNetWork(int nType) {
        int type = SysParamEntityManager.getIntParam(Constant.getContext(), Constant.SUPPORT_NETWORK_TYPE);
        if (type == 0) {
            // 网络策略开关关闭。
            return false;
        }
        int netType = -1;
        if (nType == 2) {
            // 当前请求的业务可以在任意网络下执行。但需要受用户设置的网络策略决定。
            if (type == 2) {// 网络开关是任意网络
                netType = XyUtil.checkNetWork(Constant.getContext(), 2);
            } else {
                // 网络开关是wifi
                netType = XyUtil.checkNetWork(Constant.getContext(), 1);
            }
        } else {
            // wifi网络
            netType = XyUtil.checkNetWork(Constant.getContext(), 1);// wifi

        }
        if (netType != 0) {
            return false;
        }
        // if (type == 0 || (netType == 1 && type == 1) || (type == 1 && netType
        // == 0 &&
        // DuoquUtils.getSdkDoAction().getWifiType(Constant.getContext()) == 1))
        // {
        // // 不支持网络连,或只支持wifi(接入到华为渠道时，还要判断wifi不是热点)
        // LogManager.e("HTTP", "不支持网络连,或只支持wifi: type: " + type + " netType=" +
        // netType, null);
        // return false;
        // }
        return true;
    }

    /***
     * 检测增加服务开关
     * 
     * @return
     */
    public static boolean isEnhance() {

        boolean flag = SysParamEntityManager.getBooleanParam(Constant.getContext(), Constant.SMARTSMS_ENHANCE, true);
		/*SDK-642 zhaojiangwei 20161019 start*/
        if (flag) {
			String channel = KeyManager.channel;
			if ("VMhlWdEwVNEW_LENOVO".equals(channel) ||
				"1w36SBLwVNEW_ZTE".equals(channel)) {
				flag = checkAccessNetWork(2); // 依据网络开关，控制网络
			}
		}
        /*SDK-642 zhaojiangwei 20161019 end*/
//        if ("VMhlWdEwVNEW_LENOVO".equals(KeyManager.channel) && flag == true) {
//            flag = checkAccessNetWork(2);// 依据网络开关，控制网络
//        }else  if ("1w36SBLwVNEW_ZTE".equals(KeyManager.channel) && flag == true) {
//            flag = checkAccessNetWork(2);// 依据网络开关，控制网络
//        }
        return flag;
    }

    public static boolean checkAccessNetWork(Map<String, String> extend) {
        try {
            int netType = XyUtil.checkNetWork(Constant.getContext());
            if (netType == -1)
                return false;
            int type = 1;
            if (extend != null && !extend.isEmpty()) {
                try {
                    String stringType = extend.get("SUPPORT_NETWORK_TYPE");
                    if (!StringUtils.isNull(stringType)) {
                        type = Integer.valueOf(stringType);
                    }
                } catch (Throwable e) {
                    return checkAccessNetWork(2);
                }

            } else {
                return checkAccessNetWork(2);
            }
            if (type == 0 || (netType == 1 && type == 1)) {
                // 不支持网络连,或只支持wifi
                return false;
            }
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        return true;
    }

    // // 重要网络数据的网络检查
    // public static boolean checkAccessNetWork2() {
    // try {
    // int netType = XyUtil.checkNetWork(Constant.getContext());
    // PrintTestLogUtil.printTestLog("checkAccessNetWork", "netType="
    // + netType);
    // if (netType == -1)
    // return false;
    // int type = SysParamEntityManager.getIntParam(Constant.getContext(),
    // Constant.SUPPORT_NETWORK_TYPE_MAJOR);
    //
    // PrintTestLogUtil.printTestLog("checkAccessNetWork", "type=" + type);
    //
    // if (type == 0 || (netType == 1 && type == 1)) {
    // // 不支持网络连,或只支持wifi
    // LogManager.e("HTTP", "不支持网络连,或只支持wifi: type: " + type
    // + " netType=" + netType, null);
    // return false;
    // }
    // } catch (Throwable e) {
    // // TODO: handle Throwable
    // }
    // return true;
    // }

    /**
     * 执行未加密的请求
     * 
     * @param reqeustContent
     * @param headCmd
     * @param callBack
     * @param cnum
     * @throws Throwable
     */
    public static void executePubNumServiceHttpRequest(String reqeustContent, String headCmd, XyCallBack callBack, String cnum, boolean newThread, boolean isLogin, String requestUrl, boolean isCompress) throws Exception {

        // 使用第三方自定义公众号服务
        String customPublicServer = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.CUSTOM_PUBLIC_SERVER_URL);
        if (requestUrl == null) {
            requestUrl = "";
        }
        if (StringUtils.isNull(customPublicServer)) {
            // 使用sdk内部
            // if(StringUtils.isNull(serverUrl2)){
            // serverUrl2 = "http://pubserver"+(int) (Math.random() *
            // 10+1)+".bizport.cn:9998/pubNumService/";
            // //serverUrl2 = serverUrl2;
            // }
            requestUrl = getPubNumServiceUrl() + requestUrl + "/";
        } else {
            // 使用第三方自定义公众号服务
            requestUrl = customPublicServer + requestUrl + "/";
        }
        XyHttpRunnable run = new XyHttpRunnable(requestUrl, reqeustContent, "", headCmd, isLogin, callBack, isCompress);
        if (newThread) {
            /*SDK-616 hewengao/20160918 start*/
            SmartSmsThreadPoolManager.pubInfoPool.execute(run);
            /*SDK-616 hewengao/20160918 end*/
//            executeRunnable(run);
        } else {
            run.run();
        }
    }

    // public static void executeHttpRequest(int cmd, String reqeustContent,
    // XyCallBack callBack, String url, boolean newThread)
    // throws Exception {
    // SdkXyHttpRunnable run = new cn.com.xy.sms.sdk.net.SdkXyHttpRunnable(
    // cmd, -1, url, reqeustContent, callBack);
    // if (newThread) {
    // executeRunnable(run);
    // } else {
    // run.run();
    // }
    // }

    public static void executeHttpRequest(int cmd, String reqeustContent, XyCallBack callBack, String url, Map<String, String> extend, boolean newThread) throws Exception {
        SdkXyHttpRunnable run = new cn.com.xy.sms.sdk.net.SdkXyHttpRunnable(cmd, -1, url, reqeustContent, callBack, true);
        if (newThread) {
            executeRunnable(run);
        } else {
            run.run();
        }
    }

    public static void executeHttpRequest(int cmd, int sceneType, String reqeustContent, XyCallBack callBack, String url, boolean newThread) throws Exception {
        SdkXyHttpRunnable run = new cn.com.xy.sms.sdk.net.SdkXyHttpRunnable(cmd, sceneType, url, reqeustContent, callBack, true);
        if (newThread) {
            executeRunnable(run);
        } else {
            run.run();
        }
    }

    public static void executeHttpPublicRequest(String cmd, String reqeustContent, XyCallBack callBack, String url, Map<String, String> extend) throws Exception {

        executeRunnable(new cn.com.xy.sms.sdk.net.XyHttpRunnable(url, reqeustContent, null, "990005", false, callBack, true));
    }

    public static String getUrlWithPara(String url) {
        // if(true){
        LogManager.d("HTTP", "getUrlWithPara: ", url);
        return url;
        // }
        // String imeiMd5 = XyUtil.getMid2(Constant.getContext());
        //
        // StringBuffer sb = new StringBuffer();
        // sb.append(url);
        // if(!StringUtils.isNull(imeiMd5))
        // {
        // sb.append("?imei="+ imeiMd5);
        // }
        //
        // return sb.toString();
    }

    public static void executeLoginBeforeHttpRequest(String reqeustContent, String headCmd, XyCallBack callBack, String url, boolean isCompress) throws Exception {
        // HttpHeaderDto httpHeader =null;// getHttpHeader();
        executeRunnable(new BaseHttpRunnable(url, null, reqeustContent, false, headCmd, callBack, isCompress));
    }

    public static void requestTokenIfNeed(String simIccid) {
        String token = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.HTTPTOKEN);
        if (StringUtils.isNull(token)) {
            if (StringUtils.isNull(simIccid)) {
                IccidInfo info = IccidInfoManager.queryDeftIccidInfo(Constant.getContext());
                if (info != null) {
                    simIccid = info.iccid;
                }
            }
            QueryTokenRequest(simIccid);
        }
    }
    
    public static void requestNewTokenIfNeed(Map<String,String> extendMap) {
        String token = getToken();
        if (StringUtils.isNull(token)) {            
            queryNewTokenRequest(extendMap);
        }
    }
    
    public static boolean hasNewToken(Map<String,String> extendMap){
        requestNewTokenIfNeed(extendMap);
        String token = getToken();
        if (StringUtils.isNull(token)) { 
            return false;
        }
        return true;
    }

//    请改用同步请求token方法NetUtil.syncRequestNewToken(Map<String, String> extendMap)，防止多线程重复请求token
//    public static void requestNewTokenMust(Map<String,String> extendMap) {
//        queryNewTokenRequest(extendMap);
//    }

    public static void QueryTokenRequest(String iccid) {

        try {
            XyCallBack callback = new XyCallBack() {
                @Override
                public void execute(Object... obj) {
                    // TODO Auto-generated method stub
                    if (obj != null) {
                        String resutCode = obj[0].toString();
                        if (resutCode.equals("0") && obj.length == 2) {
                            String response = obj[1].toString();
                            String token = ServerUtil.parseTokenRespose(response);
                            // Constant.setToken(token);
                            if (token != null) {
                                SysParamEntityManager.setParam(Constant.HTTPTOKEN, token);
                                SysParamEntityManager.cacheMap.put(Constant.HTTPTOKEN, token);
                            }
                        }
                    }
                }
            };
            String dataString = ServerUtil.QueryTokenRequest(iccid);
            /* SDK-504 huangzhiqiang 20160623 start */
            if (!StringUtils.isNull(dataString)) {
                NetUtil.executeAllNetHttpRequest(dataString, "990005", callback, false, true, NetUtil.REQ_QUERY_TOEKN,
                        false);
            }
            /* SDK-504 huangzhiqiang 20160623 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "QueryNewTokenRequest: ", e);
        }
    }
    
    public static void queryNewTokenRequest(Map<String,String> extendMap){
    	queryNewTokenRequest(extendMap, false, null);
    }
    
    public static void queryNewTokenRequest(Map<String,String> extendMap, boolean newthread, final XyCallBack tokenCallback) {
        try {
            XyCallBack callback = new XyCallBack() {
                @Override
                public void execute(Object... obj) {
                    // TODO Auto-generated method stub
                	boolean errorToken = true;
                    if (obj != null) {
                        try {
                            String resutCode = obj[0].toString();
                            if (resutCode.equals("0") && obj.length == 2) {
                                String response = obj[1].toString();
                              
                                JSONObject json = new JSONObject(response);
                                String token = json.optString("token");
                                
                                if (token != null) {
                                    //token存入缓存
                                    SysParamEntityManager.setParam(Constant.NEWHTTPTOKEN, token);
                                    SysParamEntityManager.cacheMap.put(Constant.NEWHTTPTOKEN, token);
                                    
                                    //aes_key存入缓存,aes_key是base64编码后的，需要解码
                                    byte[] aesKeyByte = Base64.decode(json.optString("aesKey"));
                                    SysParamEntityManager.setParam(Constant.AESKEY, RSAUtils.parseByte2HexStr(aesKeyByte));
                                    SysParamEntityManager.cacheMap.put(Constant.AESKEY, RSAUtils.parseByte2HexStr(aesKeyByte));
                                    
                                    if (tokenCallback!=null) {
                                    	errorToken = false;
                                    	XyUtil.doXycallBackResult(tokenCallback, "0",  token);
									}
                                }
                            }
                        } catch (Exception e) {
                        }
                    
                    }
                    if (errorToken && tokenCallback!=null) {
                    	XyUtil.doXycallBackResult(tokenCallback, "-1");
					}
                }
            };
            String dataString = ServerUtil.QueryNewTokenRequest();
            if (!StringUtils.isNull(dataString)) {
                NetUtil.executeNewServiceHttpRequest(NetUtil.REQ_QUERY_TOEKN, dataString, callback, newthread, true, false,
                        extendMap);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "QueryTokenRequest: ", e);

        }
    }
    
    static int useHttps = 0;

    public static boolean isUseHttps() {
        if (useHttps != 0) {
            return useHttps == 1 ? true : false;
        }
        try {
            KeyManager.initAppKey();
            /* HUAWEI-1459 huangzhiqiang 20160816 start */
            String channelArr[] = { "v22YJ3QwKINGSOFTMAIL","7N4EhHawHUAWEI2", "3GdfMSKwHUAWEI", "5Mj22a4wHUAWEICARD", "J8KeTyOROASamsungReminder", "SAMBANKVwIDAQAB", "SAMCLASSFIYVwIDAQAB", "5xKI47wSAMALL", "XYTEST" };
            /* HUAWEI-1459 huangzhiqiang 20160816 end */
            for (String c : channelArr) {
                if (c.equals(KeyManager.channel)) {
                    useHttps = 1;
                    return true;
                }
            }
        } catch (Throwable e) {
            // TODO Auto-generated catch block
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "isUseHttps: ", e);

        }
        useHttps = 2;
        return false;
    }

    public static String getPopupServiceUrl() {
        if (isUseHttps()) {
            return POPUP_SERVER_URL_HTTPS;
        }
        return serverUrl;
    }

    public static String getPubNumServiceUrl() {
        if (isUseHttps()) {
            return PUBINFO_SERVER_URL_HTTPS;
        }
        return serverUrl2;
    }

    public static String getPublicInfoServiceUrl() {
        /* KINGMAIL-46 huangzhiqiang 20170417 start */
        if (isUseHttps()) {
            return PUBLIC_INFO_SERVER_URL_HTTPS;
        }
        /* KINGMAIL-46 huangzhiqiang 20170417 end */
        return publicInfoServerUrl;
    }

    /**
     * 部分请求，任意可用网络都可以处理。
     * 
     * @param reqeustContent
     * @param headCmd
     * @param callBack
     * @param cnum
     * @throws Throwable
     */
    public static void executeAllNetHttpRequest(String reqeustContent, String headCmd, XyCallBack callBack, boolean newThread, boolean isLogin, String requestUrl, boolean isCompress) throws Exception {
        // 任意网络，受到增强开关的控制
        if (!NetUtil.isEnhance()) {
            return;
        }
        // 使用第三方自定义公众号服务
        String customPublicServer = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.CUSTOM_PUBLIC_SERVER_URL);
        if (requestUrl == null) {
            requestUrl = "";
        }
        if (StringUtils.isNull(customPublicServer)) {
            // 使用sdk内部
            requestUrl = getPubNumServiceUrl() + requestUrl + "/";
        } else {
            // 使用第三方自定义公众号服务
            requestUrl = customPublicServer + requestUrl + "/";
        }
        XyHttpRunnable run = new XyHttpRunnable(requestUrl, reqeustContent, "", headCmd, isLogin, callBack, isCompress);
        if (newThread) {
            executeRunnable(run);
        } else {
            run.run();
        }
    }
    
  
/*  public static void executeNewServiceHttpRequest(String requestUrl,String reqeustContent,
            XyCallBack callBack,
            boolean newThread, boolean isLogin, 
            boolean isCompress,Map<String,String> extendMap) throws Exception {
        executeNewServiceHttpRequest(requestUrl, reqeustContent, callBack, newThread, isLogin, isCompress, extendMap,"");
    }*/
    
    public static void executeNewServiceHttpRequest(String requestUrl,String reqeustContent,
            XyCallBack callBack,
            boolean newThread, boolean isLogin, 
            boolean isCompress,Map<String,String> extendMap) throws Exception {

        // 使用第三方自定义公众号服务
        String customPublicInfoServer = SysParamEntityManager.getStringParam(
                Constant.getContext(), Constant.CUSTOM_PUBINFO_SERVER_URL);
        if (requestUrl == null) {
            requestUrl = "";
        }
        if (StringUtils.isNull(customPublicInfoServer)) {
            requestUrl = getPublicInfoServiceUrl() + requestUrl;
        }else {
            // 使用第三方自定义公众号服务
            requestUrl = customPublicInfoServer + requestUrl;
        }
        
        
        NewXyHttpRunnable run = new NewXyHttpRunnable(requestUrl,
                reqeustContent, callBack, isLogin, isCompress,extendMap);
        if (newThread) {
            executeRunnable(run);
        } else {
            run.run();
        }
    }
    
    /* SMARTISAN-20 zhaojiangwei 20160607 start */
	public static void executeHttpRequest(final String requestUrl, final String reqeustContent, final  XyCallBack callBack) throws Exception {
		if (StringUtils.isNull(requestUrl)) {
			throw new Exception("request url is null...");
		}
		if (!checkAccessNetWork()) {
			XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, "No NetWork!");
			return;
		}
		String token = NetUtil.getToken();
		if (TextUtils.isEmpty(token)) {
			XyCallBack tokenCallback = new XyCallBack() {
				@Override
				public void execute(Object... obj) {
					// TODO Auto-generated method stub
					if (obj != null && obj.length == 2) {
						doExecuteHttpRequest(requestUrl, reqeustContent, callBack, true, false, false, null);
					}
					else {
						XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, "Error get token");
					}
				}
			};
			NetUtil.queryNewTokenRequest(null, true, tokenCallback);
		}
		else {
			doExecuteHttpRequest(requestUrl, reqeustContent, callBack, true, false, false, null);
		}
	}
	
	private static void doExecuteHttpRequest(String requestUrl, String reqeustContent,XyCallBack callBack,
			boolean newThread, boolean isLogin, boolean isCompress, Map<String, String> extendMap){		
		NewXyHttpRunnable run = new NewXyHttpRunnable(requestUrl, reqeustContent, callBack, isLogin, isCompress,
				extendMap);
		if (newThread) {
			executeRunnable(run);
		}
		else {
			run.run();
		}
	}
	/* SDK-546 zhaojiangwei 20160619 end */

    /* KINGMAIL-49 huangzhiqiang 20170411 start */
    /**
     * 执行服务器http请求
     * 
     * @param requestUrl 请求的服务器地址Url
     * @param reqeustContent 请求报文
     * @param extend 扩展参数
     * @param callBack *index0(状态): CallBackState.REQUEST_SUCCESS:当前线程或新线程，请求成功 CallBackState.ERROR:请求失败，存在异常
     *            *index1:logoName *index2:(index0 == CallBackState.REQUEST_SUCCESS):String类型 请求结果 (index0 ==
     *            CallBackState.ERROR):String类型 异常信息
     */
    public static void executeServiceHttpRequest(final String requestUrl, final String reqeustContent,
            final Map<String, String> extend, final XyCallBack callBack) {
        executeServiceHttpRequest(requestUrl, reqeustContent, extend, false, false, false, callBack);
    }

    /* KINGMAIL-49 huangzhiqiang 20170411 end */

    /* SDK-428 huangzhiqiang 20160602 start */
    /**
     * 执行服务器http请求
     * 
     * @param requestUrl 请求的服务器地址Url
     * @param reqeustContent 请求报文
     * @param extend 扩展参数
     * @param newThread 在线程池执行请求 true:线程池执行  false:当前线程执行
     * @param isLogin
     * @param isCompress 压缩请求报文 true:压缩  false:不压缩
     * @param callBack 
     *            *index0(状态):
     *                CallBackState.REQUEST_SUCCESS:当前线程或新线程，请求成功
     *                CallBackState.ERROR:请求失败，存在异常
     *            *index1:logoName 
     *            *index2:(index0 == CallBackState.REQUEST_SUCCESS):String类型 请求结果
     *                    (index0 == CallBackState.ERROR):String类型 异常信息
     */
    public static void executeServiceHttpRequest(final String requestUrl, final String reqeustContent,
            final Map<String, String> extend, boolean newThread, boolean isLogin, boolean isCompress,
            final XyCallBack callBack) {
        try {
            if (StringUtils.isNull(reqeustContent)) {
                throw new Exception("reqeustContent == null");
            }

            if (!NetUtil.isEnhance()) {
                throw new Exception("enhance == false");
            }

            if (!syncRequestNewTokenIfNeed(extend)) {
                throw new Exception("AESkey == null");
            }

            /* SDK-526 huangzhiqiang 20160713 start */
            final String token = NetUtil.getToken();
            /* SDK-526 huangzhiqiang 20160713 end */

            SdkCallBack netSdkCallBack = new SdkCallBack() {

                @Override
                public void execute(Object... obj) {
                    try {
                        if (needUpdateToken(obj)) {
                            /* SDK-526 huangzhiqiang 20160713 start */
                            NetUtil.requestNewTokenAndPostRequestAgain(requestUrl, reqeustContent,
                                    Constant.FIVE_MINUTES, false, false, false, extend, token, this);
                            return;
                            /* SDK-526 huangzhiqiang 20160713 end */
                        }

                        if (paramsError(obj)) {
                            throw new Exception("params error");
                        }
                        XyUtil.doXycallBackResult(callBack, CallBackState.REQUEST_SUCCESS, obj[1]);
                    } catch (Throwable e) {
                        LogManager.e(Constant.TAG, "NetUtil executeServiceHttpRequest execute error:",
                                e);
                        XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, e.getMessage());
                    }
                }

                private boolean paramsError(Object... obj) {
                    return obj == null || obj.length < 2 || !obj[0].toString().equals("0");
                }

                private boolean needUpdateToken(Object... obj) {
                    return obj != null && obj.length > 0
                            && obj[0].toString().equals(NewXyHttpRunnable.ERROR_CODE_TOKEN_FAILED);
                }
            };

            executeNewServiceHttpRequest(requestUrl, reqeustContent, netSdkCallBack, newThread, isLogin, isCompress,
                    extend);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "NetUtil executeServiceHttpRequest error:", e);
            XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, e.getMessage());
        }
    }

    private static final Object LOCK = new Object();
    private static String NEW_HTTP_TOKEN = null;

    /**
     * 同步方式检查是否存在Http Token
     * 
     * @param extend
     * @return true:存在Http Token false:不存在Http Token
     */
    private static boolean syncRequestNewTokenIfNeed(Map<String, String> extend) {
        if (NEW_HTTP_TOKEN == null) {
            synchronized (LOCK) {
                if (NEW_HTTP_TOKEN == null) {
                    // 获取TOKEN及AESKey信息
                    syncRequestNewToken(extend);
                    NEW_HTTP_TOKEN = getToken();
                }
            }
        }
        return !StringUtils.isNull(NEW_HTTP_TOKEN);
    }
    /* SDK-428 huangzhiqiang 20160602 end */

    /* SDK-526 huangzhiqiang 20160707 start */
    /**
     * 请求新token，如果新token请求成功则重新发送客户端请求到服务端
     * 
     * @param requestUrl
     * @param requestContent
     * @param requestInterval
     * @param newThread
     * @param isLogin
     * @param isCompress
     * @param extend
     * @param oldToken
     * @param networkCallBack
     */
    public static void requestNewTokenAndPostRequestAgain(String requestUrl, String requestContent,
            long requestInterval, boolean newThread, boolean isLogin, boolean isCompress, Map<String, String> extend,
            String oldToken, XyCallBack networkCallBack) {
        syncRequestNewToken(extend);

        String newToken = getToken();
        // token更新失败或添加请求时间记录失败(即重复请求)，不再发起请求
        if (StringUtils.isNull(newToken) || newToken.equals(oldToken)
                || !addLastServiceRequestTiem(requestContent, requestInterval)) {
            XyUtil.doXycallBackResult(networkCallBack, -9999, "server error");
            return;
        }

        try {
            executeNewServiceHttpRequest(requestUrl, requestContent, networkCallBack, newThread, isLogin, isCompress,
                    extend);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "OperatorService requestNewTokenAndPostRequestAgain error: ",
                    e);
            XyUtil.doXycallBackResult(networkCallBack, -9999, "error:" + e.getMessage());
        }
    }

    private static final LruCache<String, Long> LAST_SERVICE_REQUEST_TIEM = new LruCache<String, Long>(500);
    private static long mLastGetTokenTime = 0; // 最后获取到token数据的时间，如果请求3次后依然没法获取token也会记录时间，用于防止重复请求token
    private static int mRequestTokenCount = 0; // 请求token的次数，用于防止重复请求token

    /**
     * 添加服务端请求时间记录
     * 
     * @param request 请求内容
     * @param interval 相同请求的记录间隔，未到达记录间隔时将返回false
     * @return true:添加成功 false:添加失败
     */
    public static boolean addLastServiceRequestTiem(String request, long interval) {
        synchronized (LAST_SERVICE_REQUEST_TIEM) {
            Long time = LAST_SERVICE_REQUEST_TIEM.get(request);
            if (time == null || (time + interval) < System.currentTimeMillis()) {
                LAST_SERVICE_REQUEST_TIEM.put(request, System.currentTimeMillis());
                return true;
            }
            return false;
        }
    }

    public static boolean syncRequestNewToken(Map<String, String> extendMap) {
        // 5分钟内不重复请求token
        if (repeatRequestToken()) {
            LogManager.e(Constant.TAG, "NetUtil syncRequestNewToken error:repeat request token", null);
            return false;
        }

        try {
            synchronized (LOCK) {
                if (repeatRequestToken()) {
                    // 其它线程已经成功获取token了，不需要再次请求token，直接返回true
                    return true;
                }

                boolean result = requestNewToken(extendMap);
                mRequestTokenCount++;
                if (result || mRequestTokenCount >= 3) {
                    mLastGetTokenTime = System.currentTimeMillis();
                    mRequestTokenCount = 0;
                }
                return result;
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "NetUtil syncRequestNewToken error:", e);
        }
        return false;
    }

    private static boolean repeatRequestToken() {
        return mLastGetTokenTime + Constant.FIVE_MINUTES > System.currentTimeMillis();
    }

    private static boolean requestNewToken(Map<String, String> extendMap) {
        String oldToken = getToken();
        queryNewTokenRequest(extendMap);
        String newToken = getToken();
        return !StringUtils.isNull(newToken) && !newToken.equals(oldToken);
    }

    public static String getToken() {
        return SysParamEntityManager.getStringParam(Constant.getContext(), Constant.NEWHTTPTOKEN);
    }
    /* SDK-526 huangzhiqiang 20160707 end */
    
    /* KINGMAIL-49 huangzhiqiang 20170411 start */
    /**
     * 获取服务器头信息配置
     * 
     * @return
     */
    public static Map<String, String> getServiceHeaderConfig(String crypt) {
        if (mEmailMenuServiceExtend != null) {
            return mEmailMenuServiceExtend;
        }

        mEmailMenuServiceExtend = new HashMap<String, String>();
        mEmailMenuServiceExtend.put("channelKeyName", "chan");
        mEmailMenuServiceExtend.put("sdkVersionKeyName", "sdkver");
        mEmailMenuServiceExtend.put("uiVersionKeyName", "uiver");
        mEmailMenuServiceExtend.put("dispenseCodeKeyName", "dp");
        mEmailMenuServiceExtend.put("tokenKeyName", "tk");
        mEmailMenuServiceExtend.put("crypt", crypt);
        return mEmailMenuServiceExtend;
    }
    /* KINGMAIL-49 huangzhiqiang 20170411 end */
}
